<template>
  <div className="map-container">
    <div id="mapContainer" style="width: 100%; height: 500px;"></div>
  </div>
</template>

<script>
import loadQQMap from '../../utils/AMapLoader';

export default {
  data() {
    return {
      map: null,
      markers: [], // 存储所有的标记对象
      points: [
        {lng: 116.397428, lat: 39.90923, title: '北京天安门'}, // 示例标记点
        {lng: 116.407428, lat: 39.91923, title: '另一个地点'},
        // 可以添加更多标记点...
      ]
    };
  },
  async mounted() {
    try {
      await this.loadAndInitMap();
    } catch (error) {
      console.error('Error initializing the map:', error);
    }
  },
  methods: {
    async loadAndInitMap() {
      try {
        await loadQQMap('WCXBZ-SFQC6-UT3SS-EAKEC-3F737-Q7B4F'); // 替换为你的API_KEY
        this.$nextTick(() => {
          this.initMap();
        });
      } catch (error) {
        throw error;
      }
    },
    initMap() {
      const QQMap = window.qq.maps;
      this.map = new QQMap.Map(document.getElementById('mapContainer'), {
        center: new QQMap.LatLng(this.points[0].lat, this.points[0].lng), // 设置初始中心点为第一个标记点的位置
        zoom: 12 // 设置地图缩放级别
      });

      this.addMarkers();
    },
    addMarkers() {
      const QQMap = window.qq.maps;
      this.points.forEach(point => {
        const marker = new QQMap.Marker({
          position: new QQMap.LatLng(point.lat, point.lng),
          map: this.map,
          title: point.title,
          clickable: true,
          icon: new QQMap.MarkerImage(
            "https://imgslim.geekpark.net/uploads/image/file/3f/c7/3fc7528e4b81f385cc039c85ec0533da.jpg", // 图标URL
            new QQMap.Size(32, 32), // 图标尺寸
            new QQMap.Point(0, 0), // 原点偏移量
            new QQMap.Point(16, 32) // 锚点偏移量
          )
        });

        // 为每个标记添加点击事件监听器
        QQMap.event.addListener(marker, 'click', () => {
          alert(`你点击了 ${point.title}`);
        });

        this.markers.push(marker); // 将标记对象存储起来以便后续管理
      });
    }
  }
};
</script>

<style scoped>
/* 根据需要调整样式 */
.map-container {
  position: relative;
}

#mapContainer {
  width: 100%;
  height: 500px;
}
</style>
